package com.example.baweyplayer.activities;

import java.util.List;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.baweyplayer.R;
import com.example.baweyplayer.activities.abstracts.AbstractFullscreenActivity;
import com.example.baweyplayer.adapters.PlaylistRowAdapter;
import com.example.baweyplayer.internals.Song;
import com.example.baweyplayer.listeners.OnPlaybackEndListener;
import com.example.baweyplayer.runnables.ProgressBarUpdater;
import com.example.baweyplayer.singletons.PlaybackQueue;

public class PlayerActivity extends AbstractFullscreenActivity {

	public static enum PlaybackMode {
		DEFAULT(0, R.drawable.ic_menu_forward), REPEAT_ALL(1, R.drawable.ic_menu_revert), REPEAT_ONE(2, R.drawable.ic_menu_refresh);
		public static PlaybackMode getNext(PlaybackMode current) {
			int nextId = (current.getId() + 1) % PlaybackMode.values().length;
			for (PlaybackMode mode : PlaybackMode.values()) {
				if (mode.getId() == nextId) {
					return mode;
				}
			}
			return current;
		}

		private int id;

		private int imageId;

		private PlaybackMode(int modeId, int textId) {
			this.id = modeId;
			this.imageId = textId;
		}

		public int getId() {
			return this.id;
		}

		public int getImageId() {
			return this.imageId;
		}

	}

	private static MediaPlayer mp;
	private PlaybackMode playbackMode = PlaybackMode.DEFAULT;
	private Handler progressBarHandler;
	private ProgressBarUpdater progressBarUpdater;

	private PlaybackQueue queue;
	private int SENSITIVITY_THRESHOLD = 777;

	private PlaylistRowAdapter playlistAdapter;
	private ListView playlistView;
	private boolean shuffleEnabled = true;

	/**
	 * A test-method to find all the tracks and put them in the playback queue
	 */
	public void clearPlaylist(View view) {
		queue.clearQueue();
	}

	// called upon finishing a song playback
	public void followingTrack() {
		Log.d("baweyTest", "followingTrack call");
		Song nextTrack = null;
		nextTrack = queue.getNextTrack(playbackMode);
		loadTrack(nextTrack, true);

	}

	public MediaPlayer getMediaPlayer() {
		return mp;
	}

	public PlaybackQueue getPlaybackQueue() {
		return queue;
	}

	public Handler getProgressBarHandler() {
		return progressBarHandler;
	}

	public ProgressBarUpdater getProgressBarUpdater() {
		return progressBarUpdater;
	}

	public boolean isShuffleEnabled() {
		return shuffleEnabled;
	}

	// mp.release(); on Paused // stoped

	public void loadTrack(Song song, boolean shouldStart) {
		if (song != null) {
			mp.reset();
			try {
				mp.setDataSource(song.getAbsolutePath());
				mp.prepare();
			} catch (Throwable th) {
				th.printStackTrace();
			}
			if (shouldStart) {
				mp.start();
			} else {
				progressBarUpdater.setNeedsUpdate(true);
			}
			Log.d("baweyTest", "position: " + mp.getCurrentPosition());
			Log.d("baweyTest", "started paudio playback");
		}
	}

	public void nextTrack(View view) {
		Log.d("baweyTest", "nextTrack call");
		Song nextTrack = queue.getNextTrack(playbackMode);
		if (nextTrack != null) {
			loadTrack(nextTrack, mp.isPlaying());
		} else {
			mp.stop();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = new Intent(this, ReleaseActivity.class);
		intent.putExtra(ReleaseActivity.RELEASE_GROUP_MBID, "4ffb0057-6256-33c0-b71e-23b7f8403f12");

		Log.v("baweyLog", "creating PlayerActivity - start");
		this.setContentView(R.layout.player_layout);
		progressBarHandler = new Handler();
		if (mp == null) {
			mp = new MediaPlayer();
			mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mp.setOnCompletionListener(new OnPlaybackEndListener(this));
		}
		queue = PlaybackQueue.getInstance();
		queue.registerObserver(this);
		// launch the progress bar updater, so that it reschedules itself
		progressBarUpdater = new ProgressBarUpdater(this);
		progressBarUpdater.run();
		// super
		((ImageButton) findViewById(R.id.button7)).setImageResource(playbackMode.getImageId());
		playlistAdapter = new PlaylistRowAdapter(this);
		(playlistView = (ListView) findViewById(R.id.playlist_view)).setAdapter(playlistAdapter);
		playlistView.setOnItemClickListener(playlistAdapter.getOnItemClickListener());
	}

	@Override
	protected void onResume() {
		super.onResume();
		updatePlaylistView(queue.getPlaybackQueueList(), queue.getCurrentTrackNo());
	}

	public void pauseAudio(View view) {
		Log.d("baweyTest", "pauseAudio call");
		mp.pause();
	}

	public void playAudioIfPending(View view) {
		mp.start();
		if (mp.isPlaying()) {
			return;
		} else {
			loadTrack(queue.getCurrentTrack(), true);
		}
	}

	public void resyncPlayerWithQueue() {
		mp.stop();
		loadTrack(queue.getCurrentTrack(), true);
	}

	public void prevTrack(View view) {
		Song song = null;
		if (mp.getCurrentPosition() < SENSITIVITY_THRESHOLD) {
			Log.d("baweyTest", "switching to previous track");
			song = queue.getPreviousTrack(playbackMode);
		} else {
			Log.d("baweyTest", "rewinding track");
			song = queue.getCurrentTrack();
		}
		if (song != null) {
			loadTrack(song, mp.isPlaying());
		} else {
			mp.stop();
		}
	}

	public void setShuffleEnabled(boolean shuffleEnabled) {
		this.shuffleEnabled = shuffleEnabled;
	}

	public void stopAudio(View view) {
		mp.reset();
	}

	public void switchPlaybackMode(View view) {
		ImageButton button = (ImageButton) view;
		playbackMode = PlaybackMode.getNext(playbackMode);
		button.setImageResource(playbackMode.getImageId());
	}

	public void updatePlaylistView(final List<Song> songs, final int currentPosition) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				ImageView artwork = (ImageView) findViewById(R.id.current_song_artwork);
				TextView artist = (TextView) findViewById(R.id.current_artist);
				TextView track = (TextView) findViewById(R.id.current_title);
				TextView album = (TextView) findViewById(R.id.current_album);
				if (queue.getCurrentTrack() != null) {
					if (queue.getCurrentTrack().getImagePath() != null && queue.getCurrentTrack().getImagePath().length() > 0) {
						artwork.setImageDrawable(Drawable.createFromPath(queue.getCurrentTrack().getImagePath()));
						artwork.setVisibility(View.VISIBLE);
					} else {
						artwork.setVisibility(View.GONE);
					}
					artist.setText(queue.getCurrentTrack().getArtist());
					artist.setVisibility(View.VISIBLE);
					track.setText(queue.getCurrentTrack().getTitle());
					track.setVisibility(View.VISIBLE);
					album.setText(queue.getCurrentTrack().getAlbum());
					album.setVisibility(View.VISIBLE);
				} else {
					artwork.setVisibility(View.INVISIBLE);
					artist.setVisibility(View.INVISIBLE);
					track.setVisibility(View.INVISIBLE);
					album.setVisibility(View.INVISIBLE);
				}
				Log.d(this.getClass().getName(), "starting playlist update");
				playlistAdapter.notifyDataSetChanged();
				Log.d(this.getClass().getName(), "ending playlist update");
			}
		});
	}
}
